package cn.iocoder.yudao.module.fengdong.smartelderly.job;

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.fengdong.smartelderly.controller.admin.dayconfig.vo.DayconfigByTenantId;
import cn.iocoder.yudao.module.fengdong.smartelderly.dal.mysql.dayconfig.DayconfigMapper;
import cn.iocoder.yudao.module.fengdong.smartelderly.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

import static cn.iocoder.yudao.framework.tenant.core.context.TenantContextHolder.getTenantId;

/**
 * @author zhangjiasong
 * @description: TODO
 * @date 2023/12/19 13:55
 */
@Slf4j
@Component
public class DayconfigJob implements JobHandler {
    @Resource
    private DayconfigMapper dayconfigMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    @TenantJob
    public String execute(String param) throws Exception {
        //缴费配置集合
        List<DayconfigByTenantId> list = dayconfigMapper.selectDayconfigList();
        if (list.isEmpty()) {
            log.info("没有缴费配置要执行");
            return null;
        }
        for (int i = list.size() - 1; i >= 0; i--) {
            log.info(getTenantId()+"号租户有配置数量 "+ list.size()+"个");
            //缴费配置
            DayconfigByTenantId dayconfigByTenantId = list.get(i);

            if (null==dayconfigByTenantId.getTimingDay() || dayconfigByTenantId.getTimingDay()== 0) {
               continue;
            }

            LocalDate currentDate = LocalDate.now();
            LocalDate targetDate = currentDate.withDayOfMonth(Math.toIntExact(dayconfigByTenantId.getTimingDay()));

            if (targetDate.equals(currentDate)) {
                log.info("配置时间为当前时间===执行缴费单生成");
                // 创建 MessageProperties 对象并设置头信息
                MessageConverter converter = rabbitTemplate.getMessageConverter();

                MessageProperties messageProperties = new MessageProperties();
                messageProperties.setHeader("tenant-id", getTenantId().toString());
                Message message = converter.toMessage(JsonUtils.objToJson(dayconfigByTenantId), messageProperties);
                rabbitTemplate.convertAndSend("myDayconfigMqExchange", "DayconfigMqKey", message);
            }

        }
        return String.format("缴费配置数量为 %s 个", list.size() );
    }
}
